from bd2net import server
import threading
import time

class HealthKeeper(threading.Thread):
    def __init__(self, pool):
        super().__init__()
        self._pool = pool

    def run(self) -> None:
        for obj in self._pool:
            if not obj.isClosed():
                obj.sendMsg({
                    'action': 'healthCheck',
                    'name': 'System'
                })
            else:
                self._pool.remove(obj)
        time.sleep(5)

def main():

    connPool = list()

    def sendMsgToOthers(msg, name=None):
        if name is not None:
            print(msg)
            msg['name'] = name
        for i in connPool:
            if not i.isClosed():
                i.sendMsg(msg)
            else:
                connPool.remove(i)

    def revcCall(msg, obj):
        if msg['type'] == 'message':
            sendMsgToOthers(msg)
        elif msg['type'] == 'action':
            if msg['action'] == 'close':
                obj.close()
                connPool.remove(obj)
                time.sleep(0.5)
                sendMsgToOthers({
                    'type': 'message',
                    'content': '{} 离开了房间'.format(msg['content']),
                    'todo': 'bye',
                    'name': 'System'
                })
                sendMsgToOthers({
                    'type': 'activeCount',
                    'content': len(connPool)
                })
            if msg['action'] == 'welcome':
                time.sleep(1)
                sendMsgToOthers({
                    'type': 'message',
                    'content': '欢迎 {} 进入房间!'.format(msg['content']),
                    'todo': 'welcome',
                    'name': 'System'
                })
                sendMsgToOthers({
                    'type': 'activeCount',
                    'content': len(connPool)
                })

    def connCall(obj):
        connPool.append(obj)

    s = server.Server(12588)
    s.startServer(revcCall, connCall)
    t = HealthKeeper(connPool)
    t.start()


if __name__ == '__main__':
    main()
